package com.springboot.astra.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.astra.bean.User;
import com.springboot.astra.bean.UserRoles;
import com.springboot.astra.result.DataResult;
import com.springboot.astra.service.UserRolesService;
import com.springboot.astra.service.UserService;
import com.springboot.astra.util.DateUtils;
import com.springboot.astra.util.JwtUtils;
import com.springboot.astra.util.Md5Utils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRolesService userRolesService;
    private String avaterPath;

    @PostMapping("/getUserInfo")
    public DataResult getUserInfo(@RequestParam Map<String,String> map) {
        Integer id = Integer.valueOf(map.get("userId"));
        System.out.println(id);
        User userInfo = userService.getOneById(id);
        return DataResult.success(userInfo);
    }
    @GetMapping("/getUserInfoForUser")
    public DataResult getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtils.parseJwt(token);
        Integer userId = Integer.valueOf(claims.getId());
        User userInfo = userService.getOneById(userId);
        return DataResult.success(userInfo);
    }

    /**
     * @param
     * @return
     */
    @PostMapping("/getAll")
    public DataResult getOneById(@RequestParam Map<String,String> map)throws Exception{
        try {
            String query = map.get("query");
            Integer pagenum = Integer.valueOf(map.get("pagenum"));
            Integer pagesize = Integer.valueOf(map.get("pagesize"));
            Page<User> page = new Page<User>(pagenum, pagesize);
            IPage<User> users= userService.selectPageVo(page,query);
            return DataResult.success(users);
        }catch (Exception e) {
            return DataResult.failWithMsg("请输入有效的查询参数");
        }
    }
    @PutMapping("/addUser")
    @Transactional
    public DataResult addUser(@RequestBody User user) throws Exception {
        //设置加密密码
        user.setUserPwd(Md5Utils.encode(user.getUserPwd()));
        user.setDelete(true);
        user.setCreateTime(DateUtils.getTime());
        user.setUserImg("/img_1");
        user.setPoints(0);
        userService.insertUser(user);
        return DataResult.success(201,"success","添加用户成功");
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PutMapping("/addUserWithRegister")
    public DataResult addUserWithRegister(@RequestBody User user){
        user.setUserPwd(Md5Utils.encode(user.getUserPwd()));
        user.setDelete(true);
        user.setCreateTime(DateUtils.getTime());
        user.setUserImg("/img_1");
        user.setPoints(0);
        userService.insertUser(user);
        //分配用户角色
        //默认分配customer角色
        UserRoles userRoles = new UserRoles();
        userRoles.setUserId(user.getUserId());
        userRoles.setRoleId(2);
        userRolesService.insertUserRoles(userRoles);
        //生成token
        String token = jwtUtils.createJwt(String.valueOf(user.getUserId()),user.getUserAccount());
        return DataResult.success(token);
    }

    /**
     * 验证用户账号是否被占用
     * @param map
     * @return
     */
    @PostMapping("/userAccountIsExact")
    public DataResult userAccountIsExact(@RequestParam Map<String,String> map) {
        String userAccount = map.get("userAccount");
        User user = userService.getOneByAccount(userAccount);
        if (user != null) {
            return DataResult.failWithMsg("该账号已被注册");
        }else {
            return DataResult.success();
        }
    }
    @PutMapping("/updateStatus")
    public DataResult updateUser(@RequestBody User user) throws Exception {
        userService.updateOneById(user);
        return DataResult.success();
    }
    @PutMapping("/updateUser")
    public DataResult updateUserInfo(@RequestBody User user) throws Exception {
        userService.updateOneById(user);
        return DataResult.success();
    }
    @PostMapping ("/deleteUser")
    public DataResult deleteUserByUserId(@RequestParam Map<String,String> map) throws Exception {
        Integer userId = Integer.valueOf(map.get("userId"));
        userService.deleteOneById(userId);
        userRolesService.deleteOneById(userId);
        return  DataResult.success(200,"success","删除用户成功");
    }
    @PostMapping("/uploadAvater/avater")
    public DataResult uploadCoverImg(@RequestParam("avater") MultipartFile uploadFile ) throws Exception {
        //获得项目的类路径
        String path = ResourceUtils.getURL("classpath:").getPath();
        //空文件夹在编译时不会打包进入target中
        File uploadDir = new File(path+"/static/img/avater");
        if (!uploadDir.exists()) {
            System.out.println("上传头像路径不存在，正在创建...");
            uploadDir.mkdir();
        }
        if ( uploadFile != null) {
            //获得上传文件的文件名
            String oldName = uploadFile.getOriginalFilename();
            System.out.println("[上传的文件名]：" + oldName);
            //我的文件保存在static目录下的avatar/user
            File avatar = new File(path + "/static/img/avater/" , oldName);
            try {
                //保存图片
                uploadFile.transferTo(avatar);
                //返回成功结果，附带文件的相对路径
                return DataResult.success(200,"http://localhost:8080/static/img/avater/"+oldName,"头像上传成功");
            }catch (IOException e) {
                e.printStackTrace();
                return DataResult.failWithMsg("上传失败");
            }
        }else {
            System.out.println("上传的文件为空");
            return DataResult.failWithMsg("文件传输错误");
        }
    }
}
